/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.cenluan.tweet;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import com.cenluan.common.Const;
import com.cenluan.ext.jfinal.PkController;
import com.cenluan.kit.UUIDKit;
import com.cenluan.kit.XssKit;
import com.cenluan.login.ClearLoginInterceptor;
import com.cenluan.me.call.Call;
import com.cenluan.notification.Notification;
import com.cenluan.tweet.comment.TweetComment;
import com.cenluan.tweet.photo.TweetPhoto;
import com.cenluan.user.User;
import com.cenluan.user.UserKit;
import com.cenluan.user.log.UserLog;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 微博
 * 
 * @author peak
 * 
 */
public class TweetController extends PkController {
	/**
	 * 列表
	 */
	@ClearLoginInterceptor
	public void index() {
		User user = getSessionAttr(Const.SESSION_USER);
		String show = getPara("show");
		String order = "new";
		String createrId = null;
		if ("hot".equals(show)) {
			order = "hot";
		} else if (user != null && "mine".equals(show)) {
			createrId = user.getStr("id");
		}
		Page<Tweet> page = Tweet.dao.page(getPn(), 20, order, createrId);
		setPage(page);
		keepPara();
	}

	/**
	 * 添加
	 */
	public void add() {
		createToken();
	}

	/**
	 * 保存
	 */
	@Before({ TweetValidator.class, Tx.class })
	public void save() {
		User user = getSessionAttr(Const.SESSION_USER);
		String text = getPara("content");
		text = XssKit.escapeStr(text);
		Set<String> referers = new HashSet<String>();
		String html = UserKit.generateRefererLinks(text, referers);
		//防止@自己，这样通知自己会很奇怪
		referers.remove(user.getStr("id"));
		// 保存微博
		Tweet tweet = new Tweet();
		String tweetId = UUIDKit.generateUUID();
		tweet.set("id", tweetId);
		tweet.set("createrId", user.getStr("id"));
		tweet.set("createTime", new Date());
		tweet.set("content", html);
		if (!tweet.save()) {
			throw new RuntimeException("保存微博失败");
		}
		// 保存照片
		String[] ids = getParaValues("photoId");
		if (ids != null && ids.length > 0) {
			if (ids.length > 10) {
				throw new RuntimeException("照片超过10张");
			}
			for (String photoId : ids) {
				TweetPhoto photo = TweetPhoto.dao.findById(photoId);
				if (photo == null || photo.getStr("tweetId") != null) {
					throw new RuntimeException("无效的照片");
				}
				photo.set("tweetId", tweetId).keep("id", "tweetId");
				if (!photo.update()) {
					throw new RuntimeException("保存照片失败");
				}
			}
		}
		// 更新动态
		UserLog.save(user.getStr("id"), UserLog.TYPE_TWEET, tweetId);
		// 发通知
		for (String userId : referers) {
			Call.save(userId, Call.TYPE_TWEET, tweetId);
		}
		redirect("/tweet");
	}

	/**
	 * 删除
	 */
	public void delete() {
		User user = getSessionAttr(Const.SESSION_USER);
		Tweet tweet = Tweet.dao.findById(getPara());
		if (!user.isAdmin()
				&& !user.getStr("id").equals(tweet.getStr("createrId"))) {
			setAttr("msg", "您无权限删除微博");
			renderJson();
			return;
		}
		tweet.delete();
		if (!user.getStr("id").equals(tweet.getStr("createrId"))) {
			Notification.save(tweet.getStr("createrId"), user.getHtml()
					+ "删除了您的微博:" + tweet.getStr("content"));
		}
		setAttr("ok", true);
		renderJson();
	}

	/**
	 * 展示
	 */
	public void show() {
		Tweet tweet = Tweet.dao.findById(getPara());
		if(tweet==null){
			renderError(404);
			return;
		}
		Page<TweetComment> page = TweetComment.dao.page(getPn(), 20, getPara());
		setPage(page);
		setAttr("tweet", tweet);
	}

}
